
<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
            <a-col :md="6" :sm="8">
                <a-form-item label="奖项等级">
                    <a-select v-model="queryParam.jxdj" placeholder="请选择奖项等级" @change="handleSelectdj">
                      <a-select-option value="1">一等奖</a-select-option>
                      <a-select-option value="2">二等奖</a-select-option>
                    </a-select>
                </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
                <a-form-item label="分组名称">
                    <a-select v-model="queryParam.fzid" placeholder="请选择复审分组" @change="handleSelectFz">
                      <a-select-option v-for="item in fsfzlist" :key="item.id" :value="item.id">
                          {{item.fs_fz_mc}}
                      </a-select-option>
                    </a-select>
                </a-form-item>
            </a-col>
            <a-col :sm="8">
                <a-form-item label="">
                    <!-- <a-button style="margin-right:10px;" type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <a-button style="margin-right:10px;" type="primary" @click="searchReset" icon="reload">重置</a-button> -->
                    <a-button v-if="isTp" style="margin-right:10px;" type="primary" disabled>已投票</a-button>
                    <template v-else>
                        <a-button v-if="userRole==3" style="margin-right:10px;" type="primary" @click="handleSubmit">提交</a-button>
                    </template>
                    <a-button type="primary" style="margin: 0px;" @click="submitQrode()" :disabled="disabledSig">签名</a-button>
                    <a-button type="primary" style="margin: 0px 0 0 10px;" :disabled="!isTp || !disabledSig" @click="ratingPreview(1)">投票预览</a-button>
                </a-form-item>
            </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- table区域-begin -->
    <div>
      <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div> -->

        <a-table
            ref="table"
            size="middle"
            :scroll="{x:'100%'}"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            class="j-table-force-nowrap"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
            <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
            <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
            <a-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="downloadFile(text)">
                下载
            </a-button>
            </template>
            <template slot="cgmc" slot-scope="text, record">
                <span>{{record.cxj_mc_zw}}<img class="pointer" style="margin-left: 10px;" @click="viewDetail(record)" src="@/assets/img/xszt.png"/></span>
            </template>
            <template slot="tpjg" slot-scope="text, record">
                <!-- 1-同意，2-不同意，0-弃权 -->
                <a-radio-group default-value="1" v-model="record.tp_jg">
                    <a-radio value="1">同意</a-radio>
                    <a-radio value="2">不同意</a-radio>
                    <a-radio value="0">弃权</a-radio>
                </a-radio-group>
            </template>
            <!-- <span slot="action" slot-scope="text, record">
                <a @click="handleSubmit(record)">提交</a>
            </span> -->
        </a-table>
    </div>
    <!-- 二维码 -->
    <a-modal
        :visible="qrcodeVisible"
        @cancel="handleCancel()"
        title="请用手机扫二维码签名"
        centered
        :footer="null"
        width="400px"
        height="400px"
    >
        <vue-qr :text="imgQrUrl" :size="360" :margin="0"></vue-qr>
    </a-modal>
    <!-- pdf -->
    <view-pdf :params="pafParams" :showPdf="showpdf" @reset="getQrUrl" :pafBtn="pafBtn" path="cxjZxpdTpJs"></view-pdf>
    <cxj-fs-fz-xm-modal ref="modalForm" @ok="modalFormOk"></cxj-fs-fz-xm-modal>
  </a-card>
</template>

<script>
import VueQr from 'vue-qr'
import viewPdf from '@/views/cxj/viewPdf'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CxjFsFzXmModal from './modules/CxjFsFzXmModal'
import { filterObj } from '@/utils/util';
import moment from 'moment'
import {
    getAction,
} from "@/api/manage"
import {
    sysCxjFlCxjsbList,
    cxjzxpdSubmitTpJs,
    cxjzxpdSubmitStatusTpJs,
    cxjzxpdIsShowSig,
    cxjzxpdGetQrcodeTpJs
} from "@/api/api"
import Vue from 'vue'
import { USER_INFO, ACCESS_TOKEN } from "@/store/mutation-types"
export default {
    name: 'CxjFsFzXmList',
    mixins:[mixinDevice],
    // mixins:[JeecgListMixin, mixinDevice],
    components: {
      CxjFsFzXmModal,
      VueQr,
      viewPdf
    },
    data () {
      return {
        pdfFilePath: '',
        showpdf: false,
        pafBtn: false,
        pafParams: {},
        qrcodeVisible: false,
        signStatus: false,
        imgQrUrl: '',
        description: '复审分组项目表管理页面',
        disabledSig: true,
        // 表头
        columns: [
            {
                title: '序号',
                dataIndex: '',
                key:'rowIndex',
                width:'4%',
                align:"center",
                customRender:function (t,r,index) {
                return parseInt(index)+1;
                }
            },
            {
                title:'成果编号',
                align:"center",
                width:'9%',
                dataIndex: 'cxj_xmbh'
            },
            {
                title:'成果名称',
                align:"left",
              width:'27%',
                dataIndex: 'cxj_mc_zw',
                scopedSlots: { customRender: 'cgmc' }
            },
            {
                title:'申报单位',
                align:"center",
              width:'15%',
                dataIndex: 'sbdw_qymc'
            },
            {
                title:'推荐单位',
                align:"center",
              width:'11%',
                dataIndex: 'jttjdw_mc'
            },
            {
                title:'总得分',
                align:"center",
              width:'6%',
                dataIndex: 'df_zdf'
            },
            {
                title:'推荐奖项',
                align:"center",
              width:'6%',
                dataIndex: 'xm_hjdj_show'
            },
            {
                title:'投票意见',
                align:"center",
              width:'22%',
                dataIndex: 'tp_jg',
                scopedSlots: { customRender: 'tpjg' }
            },
            // {
            //     title: '操作',
            //     dataIndex: 'action',
            //     align:"center",
            //     fixed:"right",
            //     width:147,
            //     scopedSlots: { customRender: 'action' }
            // }
        ],
        url: {
            list: "/cxj/cxjZxpdTpJs/cxjzxpd_tpxmListZj",
            delete: "/cxj/cxjFsFzXm/delete",
            deleteBatch: "/cxj/cxjFsFzXm/deleteBatch",
            exportXlsUrl: "/cxj/cxjFsFzXm/exportXls",
            importExcelUrl: "cxj/cxjFsFzXm/importExcel",
            cxjfs_fzlist: "/cxj/cxjFsFz/cxjfs_fzlist",
        },
        cxjSbList: [],
        fsfzlist: [],
        /* 年份参数开始 */
        yearShowOne:false,
        shijian: moment(new Date()).format('YYYY'),
        /* 年份参数结束 */

        /* 列表参数开始 */
        queryParam: {},
        dictOptions:{},
        superFieldList:[],
        fileStatus: "",
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        isorter: {
            column: 'createTime',
            order: 'desc',
        },
        dataSource: [],
        ipagination: {
            current: 1,
            pageSize: 30,
            pageSizeOptions: ['30', '60', '90'],
            showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
        },
        tp_jg:'0',
        isTp: false,
        /* 列表参数结束 */
        userRole: sessionStorage.getItem('role')
      }
    },
    created() {
        this.$set(this.dictOptions, 'isValid', [{text:'是',value:'Y'},{text:'否',value:'N'}])
        this.getSuperFieldList();
        this.getsysCxjFlCxjsbList();
        this.getcxjfs_fzlist();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
  methods: {
        moment,
        handleCancel() {
            clearInterval(this.qrTimer)
            this.qrcodeVisible = false;
        },
        // 评分预览
        ratingPreview(flag) {
            this.pafBtn = flag == 1 ? false : true
            this.pafParams = {
                fzid: 111
            }
            this.showpdf = !this.showpdf
        },
        // 查询签名状态
        checkSignStatus(params) {
            clearInterval(this.qrTimer)
            this.qrTimer = setInterval(() => {
                cxjzxpdSubmitStatusTpJs(params,'cxjZxpdTpJs').then(res=>{
                    if (res.result) {
                        clearInterval(this.qrTimer)
                        this.qrcodeVisible = false
                        this.ratingPreview(1)
                        this.signStatus = true
                        this.$message.success("签名成功！")
                        this.isShowSigFun()
                    }
                }).catch(err => {
                    this.$message.error("查询签名状态失败！")
                })
            }, 1000)
        },
        submitQrode() {
            this.getQrUrl()
        },
        // 查询二维码地址
        getQrUrl() {
            let formData = new FormData();
            cxjzxpdGetQrcodeTpJs(formData,'cxjZxpdTpJs').then(res=>{
                if (res.code === 200) {
                    this.imgQrUrl = `${window.location.origin}${res.result}&path=cxjZxpdTpJs`
                    this.qrcodeVisible = true
                    this.checkSignStatus({
                        fzid: 1
                    })
                } else {
                    this.$message.error(res.message)
                }
            }).catch(err => {
                this.$message.error("查询二维码失败！")
            })
        },
        downfn(name, res) {
            const _res = res;
            let blob = new Blob([_res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
            let downloadElement = document.createElement("a");
            let href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = name; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
        },
        viewDetail(item){
            console.log('成果推荐管理',item)
            let token = Vue.ls.get(ACCESS_TOKEN);
            sessionStorage.setItem('token', token);
             let routeData = this.$router.resolve({
                path: '/shenbao/declare',
                query: {
                    type: '11',
                    cxj_cxj_id: item.cxj_cxj_id,
                    isHead: 2,
                    from: 'zj',
                    cxj_xmbh: item.cxj_xmbh,
                    cxj_mc_zw: item.cxj_mc_zw
                }
            });
            window.open(routeData.href, '_blank');
        },
        handleImport() {
          const choosefile = document.querySelector('#fscg');
          choosefile.click();
        },
        /* 获取成果类别开始 */
        getsysCxjFlCxjsbList(){
            sysCxjFlCxjsbList(null).then(res=>{
                if (res.success) {
                    this.cxjSbList = res.result;
                }
            })
        },
        /* 获取成果类别结束 */
        getcxjfs_fzlist() {
          getAction(this.url.cxjfs_fzlist,  {flid: '11'}).then((res) => {
                if (res.success) {
                    this.fsfzlist = res.result.records || res.result;
                    this.fzid = this.fsfzlist[0].id;
                    this.queryParam.fzid = this.fzid;
                    this.queryParam.jxdj = '1';
                    this.loadData();
                }
            })
        },
        handleSelectdj(value) {
            this.queryParam.jxdj = value;
            this.loadData(1);
        },
        handleSelectFz(value) {
            this.queryParam.fzid = value;
            this.loadData(1);
        },
        /* 获取列表固定格式开始 */
        getQueryField() {
            //TODO 字段权限控制
            var str = "id,";
            this.columns.forEach(function (value) {
                str += "," + value.dataIndex;
            });
            return str;
        },
        // 获取分组项目
        loadData(arg) {
            if (!this.url.list) {
                this.$message.error("请设置url.list属性!")
                return
            }
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.ipagination.current = 1;
            }
            var params = this.getQueryParams();//查询条件
            this.loading = true;
            // cxjzxpdSubmitStatusTpJs(params,'cxjZxpdTpJs').then(res=>{
            //     if (res.result) {
            //         this.signStatus = true
            //     } else {
            //         this.signStatus = false
            //     }
            // }).catch(err => {
            //     this.$message.error("查询签名状态失败！")
            // })
            this.isShowSigFun()
            // 分组id
            getAction(this.url.list, params).then((res) => {
                if (res.success) {
                    //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                    this.dataSource = res.result.tpxmList || res.result;
                    this.isTp = res.result.isTp;
                    // this.dataSource = res.result.tpxmList[0];
                    console.log('213123123312',this.dataSource)
                    this.dataSource.map(item=>{
                        // item.tp_jg = "1"
                        if (!item.tp_jg){
                            item.tp_jg = "1"
                        }
                    })
                    if (res.result.total) {
                        this.ipagination.total = res.result.total;
                    } else {
                        this.ipagination.total = 0;
                    }
                    //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                }
                if (res.code === 510) {
                    this.$message.warning(res.message)
                }
                this.loading = false;
            })
        },
        onSelectChange(selectedRowKeys, selectionRows) {
            this.selectedRowKeys = selectedRowKeys;
            this.selectionRows = selectionRows;
        },
        onClearSelected() {
            this.selectedRowKeys = [];
            this.selectionRows = [];
        },
        modalFormOk() {
            // 新增/修改 成功时，重载列表
            this.loadData();
            //清空列表选中
            this.onClearSelected()
        },
        handleTableChange(pagination, filters, sorter) {
            //分页、排序、筛选变化时触发
            //TODO 筛选
            if (Object.keys(sorter).length > 0) {
                this.isorter.column = sorter.field;
                this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
            }
            this.ipagination = pagination;
            this.loadData();
        },
        
        getQueryParams() {
            //获取查询条件
            let sqp = {}
            if (this.superQueryParams) {
                sqp['superQueryParams'] = encodeURI(this.superQueryParams)
                sqp['superQueryMatchType'] = this.superQueryMatchType
            }
            this.queryParam.shijian = this.shijian;
            var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
            param.field = this.getQueryField();
            param.pageNo = this.ipagination.current;
            param.pageSize = this.ipagination.pageSize;
            return filterObj(param);
        },
        handleAdd: function () {
            this.$refs.modalForm.add();
            this.$refs.modalForm.title = "新增";
            this.$refs.modalForm.disableSubmit = false;
        },
        handleSubmit: function () {
            var jgarr = [];
            let self = this;
            /* this.dataSource.forEach(element => {
                jgarr.push(element.tp_jg)
            });
            cxjzxpdSubmitTpJs({
                tpjgs:jgarr.join(','),
                fzid: this.queryParam.fzid,
                jxdj: this.queryParam.jxdj
            }).then(res=>{
                if (res.code=='200') {
                    this.$message.success(res.result);
                    this.loadData();
                } else {
                    this.$message.error('提交失败');
                }
            }) */
            this.$confirm({
                title: '提交后不可修改，是否提交？',
                onOk() {
                    self.dataSource.forEach(element => {
                        jgarr.push(element.tp_jg)
                    });
                    cxjzxpdSubmitTpJs({
                        tpjgs:jgarr.join(','),
                        fzid: self.queryParam.fzid,
                        jxdj: self.queryParam.jxdj
                    }).then(res=>{
                        if (res.code=='200') {
                            self.$message.success(res.result);
                            self.loadData();
                        } else {
                            self.$message.error('提交失败');
                        }
                    })
                },
                onCancel() {},
            });
        },
        isShowSigFun(){
          cxjzxpdIsShowSig(this.params,'cxjZxpdTpJs').then(res=>{
            if (res.result) {
              this.disabledSig = false
            } else {
              this.disabledSig = true
            }
          }).catch(err => {
            this.$message.error("查询签名状态失败！")
          })
        },
        searchQuery() {
            this.loadData(1);
        },
        searchReset() {
            this.queryParam = {};
            // this.flid = "";
            this.shijian = moment(new Date()).format('YYYY');
            this.queryParam.shijian = this.shijian;
            this.getcxjfs_fzlist();
            this.loadData(1);
        },
        /* 获取列表固定格式结束 */


        /* 年份控制开始 */

        openChangeOne(status){
            //status是打开或关闭的状态
            if(status){
                this.yearShowOne =  true;
            }
        },
        // 得到年份选择器的值
        panelChangeOne(value){
            // params.shijian = value;
            this.shijian = moment(value).format('YYYY');
            this.queryParam.shijian = this.shijian;
            this.yearShowOne = false
        },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'cxjFsFzId',text:'复审分组ID',dictCode:''})
        fieldList.push({type:'string',value:'cxjCxjId',text:'成果ID',dictCode:''})
        fieldList.push({type:'string',value:'sysZjId',text:'主审专家ID',dictCode:''})
        fieldList.push({type:'string',value:'shijian',text:'年度',dictCode:''})
        fieldList.push({type:'string',value:'cxjFsSjId',text:'复审时间',dictCode:''})
        fieldList.push({type:'string',value:'bz1',text:'备注1',dictCode:''})
        fieldList.push({type:'string',value:'bz2',text:'备注2',dictCode:''})
        fieldList.push({type:'switch',value:'isValid',text:'是否有效'})
        fieldList.push({type:'int',value:'xmXh',text:'排序号',dictCode:''})
        this.superFieldList = fieldList
      }
    }
}
</script>
<style scoped>
  @import '~@assets/less/common.less';
  /deep/.ant-table-thead > tr > th .ant-table-header-column {
    width:100%;
    text-align: center!important;
  }
  /deep/.ant-table-thead > tr > th {
    font-size: 14px!important;
    padding:8px 3px!important;
  }
  /deep/.ant-table-tbody > tr > td {
    word-break: break-all;
    white-space: normal;
    word-wrap:break-word;
    font-size:14px;
    padding:3px 3px!important;
  }
</style>